package com.alexeyhanin.tapestry.goodies.util.select;

import org.apache.tapestry5.ioc.services.ClassPropertyAdapter;
import org.apache.tapestry5.ioc.services.PropertyAccess;
import org.apache.tapestry5.ioc.services.PropertyAdapter;

import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author aha
 * @since 2009.28.11
 *        $Id: FormattingPropertyAdapterFactory.java 15 2009-11-30 17:52:21Z gagarin61 $
 */
public class FormattingPropertyAdapterFactory {

    // TODO support escape character
    private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\{([^}]+)\\}");

    private Class<?> clazz;
    private PropertyAccess propertyAccess;

    public FormattingPropertyAdapterFactory(Class<?> clazz, PropertyAccess propertyAccess) {
        this.clazz = clazz;
        this.propertyAccess = propertyAccess;
    }

    public FormattingPropertyAdapter create(String format) {
        final StringBuffer sb = new StringBuffer();
        final Matcher matcher = PLACEHOLDER_PATTERN.matcher(format);
        final List<PropertyAdapter> adapters = new LinkedList<PropertyAdapter>();
        final ClassPropertyAdapter classPropertyAdapter = propertyAccess.getAdapter(clazz);
        while (matcher.find()) {
            matcher.appendReplacement(sb, "%s");
            final String property = matcher.group(1);
            final PropertyAdapter propertyAdapter = classPropertyAdapter.getPropertyAdapter(property);
            adapters.add(propertyAdapter);
        }
        matcher.appendTail(sb);

        return new FormattingPropertyAdapter(sb.toString(), adapters.toArray(new PropertyAdapter[adapters.size()]));
    }

}
